<template>
	<el-dialog v-model="isVisible" title="部分退款" width="500px" :before-close="handleClose">
		<el-form ref="formRef" class="good-service-form" :model="form" :rules="rules" label-width="120px" inline>
			<el-form-item label="退款金额" prop="amount">
				<el-input-number
					v-model="form.amount"
					:controls="false"
					class="num-left"
					:min="0"
					:max="fenToYuan(row?.availableRefundAmount)"
					placeholder="输入退款金额"
				/>
				<div class="font12 color-warning">可退款金额{{ fenToYuan(row?.availableRefundAmount) }}</div>
			</el-form-item>
			<el-form-item label="退款原因" prop="reason">
				<el-input type="textarea" v-model="form.reason" :maxlength="100" placeholder="输入退款原因" />
			</el-form-item>
			<el-form-item label="上传附件" prop="attachment">
				<uploadImage v-model:file-list="form.attachment" :limit="1" :fileSize="1">
					<template #tip> 请上传审批完成附件图片 </template>
				</uploadImage>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" v-debounce="submit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="tsx">
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, watch } from 'vue';
import { fetchOrderPartRefund } from '/@/api/order';
import uploadImage from '/@/components/upload/image.vue';
import { fenToYuan } from '/@/utils/commonFunction';

const props = defineProps({
	// 列表内容
	visible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => null,
	},
});

const emit = defineEmits(['handleClose']);

const isVisible = ref(false);

const formRef = ref();
const form = ref<any>({});

//校验规则
const rules = reactive<FormRules<any>>({
	amount: [{ required: true, trigger: 'blur', message: '退款金额不能为空' }],
	reason: [{ required: true, trigger: 'blur', message: '退款原因不能为空' }],
	attachment: [{ required: true, trigger: ['blur', 'change'], message: '附件不能为空' }],
});

watch(
	() => props.visible,
	(val) => {
		isVisible.value = val;
	},
	{
		immediate: true,
	}
);

const submit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const res = await fetchOrderPartRefund({
				...form.value,
				id: props.row.id,
				amount: form.value.amount * 100,
				attachment: form.value.attachment.map((v: any) => v.url).join(','),
			});
			if (res.code == 200) {
				ElMessage.success('部分退款完成');
				handleClose(true);
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const handleClose = (success?: boolean) => {
	form.value = {};
	formRef.value.resetFields();
	emit('handleClose', success === true);
};
</script>

<style lang="scss">
.good-service-form {
	.el-form-item {
		width: 90%;
		.el-input-number {
			width: 100%;
		}
	}
}
</style>
